#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from models.teacher_studentmanagement import t_teacher_studentmanagement
from utils import commons
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN


class TeacherStudentmanagementService(object):

    @classmethod
    def joint_query(cls, **kwargs):
    
        page = int(kwargs.get('Page', 1))
        size = int(kwargs.get('Size', 10))

        filter_list = []
    
        if kwargs.get('student_id') is not None:
            filter_list.append(t_teacher_studentmanagement.columns['student_id'] == kwargs.get('student_id'))
        if kwargs.get('student_name') is not None:
            filter_list.append(t_teacher_studentmanagement.columns['student_name'] == kwargs.get('student_name'))
        if kwargs.get('lesson_name') is not None:
            filter_list.append(t_teacher_studentmanagement.columns['lesson_name'] == kwargs.get('lesson_name'))
        if kwargs.get('phone') is not None:
            filter_list.append(t_teacher_studentmanagement.columns['phone'] == kwargs.get('phone'))

        try:
            teacherstudentmanagement_info = db.session.query(t_teacher_studentmanagement).filter(*filter_list)
            
            count = teacherstudentmanagement_info.count()
            pages = math.ceil(count / size)
            teacherstudentmanagement_info = teacherstudentmanagement_info.limit(size).offset((page - 1) * size).all()
            results = commons.query_to_dict(teacherstudentmanagement_info)

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
    
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
            
        finally:
            db.session.close()
